# 数据库操作
import configparser

import pymysql

# 创建 ConfigParser 对象
config = configparser.ConfigParser()

# 读取配置文件
config.read('config/config.ini')

# 获取配置信息
host = config['Database']['host']
port = int(config['Database']['port'])
username = config['Database']['username']
password = config['Database']['password']
dbname = config['Database']['dbname']
charset = config['Database']['charset']


# 连接数据库
def getConnection():
    db = pymysql.Connect(host=host, port=port, user=username, passwd=password, db=dbname, charset=charset)
    return db


# 查询数据
def getData(sql):
    db = getConnection()
    cursor = db.cursor()
    data = None  # 保存返回数据
    try:
        cursor.execute(sql)
        data = cursor.fetchall()
    except Exception as e:
        print("异常：", e)
    finally:
        cursor.close()
        db.close()
    return data


# 更新数据
def writeData(sql):
    db = getConnection()
    cursor = db.cursor()
    r = 0
    try:
        r = cursor.execute(sql)
        db.commit()
        print("---------数据已更新---------！" + "受影响行数:", r)
    except Exception as e:
        print("异常：", e)
    finally:
        cursor.close()
        db.close()
    return r  # 返回受影响的行数
